<?php

namespace app\services;


use app\traits\Page;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserTeam;
use plugin\admin\app\model\UserTeamMonthData;
use plugin\admin\app\model\UserUpline;
use support\Db;

class UserTeamService
{
    public static function children($page, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $query = Db::table('wa_users', 'u')
            ->select(['u.id', 'u.level', 'up.nickname', 'up.avatar', 'u.mobile', 'ut.team_consume', 'ut.team_count',  'u.join_time'])
            ->join(Db::raw('wa_user_profiles as up'), 'up.user_id', '=', 'u.id', 'left')
            ->join(Db::raw('wa_user_teams as ut'), 'ut.user_id', '=', 'u.id', 'left')
            ->where('u.parent_id', get_user_id());


        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('ut.team_count')->get()->toArray();

        $levels = UserLevel::getLevelMap();

        foreach ($list as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $item['level_text'] = $levels[$item['level']];

            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function teamInfo()
    {
        return UserTeam::where('user_id', get_user_id())->first()->toArray();
    }

    public static function performance($id = null)
    {
        $id = is_null($id) ? get_user_id() : $id;
        $teamInfo = UserTeam::where('user_id', $id)->first();

        $children = User::where('parent_id', $id)->get()->toArray();
        $childrenIds = array_column($children, 'id');

        $bigAreaTeamInfo = UserTeam::whereIn('user_id', $childrenIds)->orderByDesc('team_consume')->first();
        $bigArea = $bigAreaTeamInfo['team_consume'] ?? 0;

        $smallArea = UserTeam::whereIn('user_id', $childrenIds)->where('user_id', '<>', $bigAreaTeamInfo['user_id'] ?? 0)->sum('team_consume');

        return ['total' => $teamInfo['team_consume'], 'big_area' => $bigArea, 'small_area' => $smallArea];
    }

    public static function addOrderCount($order)
    {
        $user = User::where('id', $order['user_id'])->first();

        $parentId = $user['parent_id'];

        if ($user['level'] != 2 && $parentId > 0) {
            UserTeam::where('user_id', $parentId)->increment('recommend_vip_count', 1);

            TeamReleaseLogService::incrementRecommendCount($parentId, $order['user_id']);
        }

        $parentIds = UpLineService::get($order['user_id']);

        if ($parentId > 0) {
            UserTeam::where('user_id', $parentId)->increment('recommend_order_count', 1);
//            UserTeam::where('user_id', $parentId)->increment('current_month_recommend_order_count', 1);
        }

        $parentIds[] = $order['user_id'];

        UserTeam::whereIn('user_id', $parentIds)->increment('team_consume', $order['price']);
        UserTeam::whereIn('user_id', $parentIds)->increment('team_order_count', 1);
//        UserTeam::whereIn('user_id', $parentIds)->increment('current_month_order_count', 1);

        foreach ($parentIds as $parentId) {
            $teamInfo = UserTeam::where('user_id', $parentId)->first();

            TeamReleaseLogService::check($parentId, $teamInfo['team_consume']);
        }

    }

    public static function clearCurrentMonthRecommendOrderCount()
    {
        $teams = UserTeam::where('current_month_recommend_order_count', '>', 0)->get()->toArray();

        foreach ($teams as $team) {
            $month = date('Y-m', strtotime('-1 month'));

            if (UserTeamMonthData::where('day', $month)->where('user_id', $team['user_id'])->count() == 0) {
                UserTeamMonthData::insert([
                    'user_id' => $team['user_id'],
                    'day' => $month,
                    'recommend_order_count' => $team['current_month_recommend_order_count'],
                    'order_count' => $team['current_month_order_count'],
                ]);

                UserTeam::where('id', $team['id'])->update(['current_month_recommend_order_count' => 0, 'current_month_order_count' => 0]);
            }
        }

    }
}